package com.dc.commons.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class DcInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger=LoggerFactory.getLogger(DcInterceptor.class);
	private String logBack="logBack";
	@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
		if(request.getSession().getAttribute("logBack")!=null){
			MDC.put(logBack, "debug");// 可能一直就是这个搞错了
		}
		MDC.put("username", "admin");
		logger.debug("comeing");
		
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
       // System.out.println("request结束后");
        long startTime = (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        request.setAttribute("handlingTime", endTime - startTime);
    }

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		MDC.remove(logBack);
		MDC.remove("useername");
	}
    
    
}
